package com.traffic.between.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
 * 流量加密算法
 * 
 * @author Guoxing
 *
 */
public class EncrpytionUtil {
	public static String suffix = "PIEncrypt";

	private static byte[] salt = { 84, 94, -60, 118, 67, -20, -55, -70 };

	private static byte[] iv = { 79, 76, -120, -36, -61, -72, 91, 50 };

	private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };

	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; ++i) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String str2MD5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			return byteArrayToHexString(md.digest(str.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("不支持MD5算法");
		}
	}

	public static byte[] str2MD5Bytes(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			return md.digest(str.getBytes());
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("不支持MD5算法");
		}
	}

	public static String encryptString(String p_value) {
		try {
			Cipher ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			IvParameterSpec ivp = new IvParameterSpec(iv);
			DESKeySpec desKeySpec = new DESKeySpec(salt);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			ecipher.init(1, secretKey, ivp);

			byte[] utf8 = p_value.getBytes("UTF8");
			byte[] enc = ecipher.doFinal(utf8);

			return new String(Base64.encodeBase64(enc)) + suffix;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String decryptString(String p_value) {
		try {
			Cipher dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			IvParameterSpec ivp = new IvParameterSpec(iv);
			DESKeySpec desKeySpec = new DESKeySpec(salt);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			dcipher.init(2, secretKey, ivp);

			p_value = p_value.substring(0, p_value.length() - suffix.length());

			byte[] dec = Base64.decodeBase64((p_value == null) ? new byte[0] : p_value.getBytes());

			byte[] utf8 = dcipher.doFinal(dec);
			String result = new String(utf8, "UTF8");

			if (result.endsWith("\r\n"))
				result = result.substring(0, result.length() - 2);
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String decryptByAESForJS(String content, String keyseed) throws Exception {
		SecretKeySpec key = getKeySpecFromBytes(keyseed.toUpperCase());
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(2, key);
		String result = new String(cipher.doFinal(hex2byte(content.getBytes("UTF-8"))));

		return result.trim();
	}

	private static SecretKeySpec getKeySpecFromBytes(String strBytes) throws NoSuchAlgorithmException {
		SecretKeySpec spec = new SecretKeySpec(hex2byte(strBytes.getBytes()), "AES");

		return spec;
	}

	public static byte[] hex2byte(byte[] b) {
		if (b.length % 2 != 0) {
			throw new IllegalArgumentException("长度不是偶数!");
		}
		byte[] b2 = new byte[b.length / 2];

		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[(n / 2)] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	public static byte[] hex2byte(String str) {
		try {
			byte[] b = str.getBytes("UTF-8");
			if (b.length % 2 != 0)
				throw new IllegalArgumentException("长度不是偶数");
			byte[] b2 = new byte[b.length / 2];
			for (int n = 0; n < b.length; n += 2) {
				String item = new String(b, n, 2);
				b2[(n / 2)] = (byte) Integer.parseInt(item, 16);
			}
			return b2;
		} catch (Exception e) {
		}
		return null;
	}
}